import random
import re
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from user.models import UserModel
from user.ser import UserSer
from utils import myredis
from utils.myjwt import jwtweb
from utils.mymessage import send_message
from utils.myredis import redistoll


# Create your views here.
class UserView(APIView):
    def post(self, request):
        data={}
        account=request.data.get('account')
        password=request.data.get('password')
        if account=="" or password=="":
            return Response({'msg':400,'message':'账号或密码不允许为空！！！！'})
        #保存到数据库
        #判断account是否为邮箱或手机号
        if re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$",account):
            data['email']=account
        elif re.match(r"^1[3456789]\d{9}$",account):
            data['phone']=account
        else:
            data['username']=account
        data['password']=password
        ser=UserSer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":'注册成功！！！'})
        else:
            return Response({"msg":ser.errors})

class LoginView(APIView):
    def post(self,request):
        account=request.data.get('account')
        password=request.data.get('password')
        if re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", account):
            usermodel=UserModel.objects.filter(email=account)
        elif re.match(r"^1[3456789]\d{9}$", account):
            usermodel=UserModel.objects.filter(phone=account)
        else:
            usermodel=UserModel.objects.filter(username=account)
        if usermodel:
            #查询数据
            if usermodel[0].password==password:
                token=jwtweb.gettoken(usermodel[0].id,account)
                return Response({'msg':"登录成功！！","token":token,"id":usermodel[0].id,"code":200})
            else:
                return Response({"msg":'密码错误！！',"code":402})
        else:
            return Response({"msg":"账号不存在！！！","code":402})

class LoginByCode(APIView):
    def post(self,request):
        #如果手机号存在  就是登陆  如果不存在就是注册  添加记录到数据库同时设置初始密码为000000
        account=request.data.get('account')
        code=request.data.get('code')
        #先判断验证码
        if redistoll.getstr(account)!=code:
            return Response({"msg":"验证码错误","code":402})
        else:
            #验证码正确
            userinfo=UserModel.objects.filter(phone=account)
            #存在账号
            if userinfo:
                token=jwtweb.gettoken(userinfo[0].id,account)
                return Response({"msg":"登陆成功","token":token,"id":userinfo[0].id,"code":201})
            else:
                #不存在
                data={"phone":account,"password":'0000'}
                ser=UserSer(data=data)
                if ser.is_valid():
                    ser.save()
                    token=jwtweb.gettoken(ser.data['id'],account)
                    return Response({"msg": "登陆成功", "token": token, "id": ser.data['id'], "code": 201})

        return Response(redistoll.getstr("logincode"))

class SendCode(APIView):
    def post(self,request):
        #1.获取手机号
        phone=request.data.get('account')
        #写一个正则验证手机号 自己写  然后校验通过后再发验证码
        # if re.match(r"^1[3456789]\d{9}$",phone):
            #2.生成验证码  生成一个四位数的随机数
        code=str(random.randint(1000,9999))
        if send_message(phone,code):
            #存到redis，并且给前端返回
            redistoll.setex(phone, code, 60 * 2)
            return Response({'msg': "发送成功"})
        #调用验证码的函数
        else:
            return Response({'msg':"发送失败"})


